<template>
  <VPage :leftConfig="{collapse: true, width: 230}">
    <template #left>
      <DeliveryPlan ref="deliveryPlanRef" type="sku" @changeDeliverTime="changeDeliverTime"></DeliveryPlan>
    </template>
    <VTable ref="tableRef" v-bind="tableOptions">
      <template #form="{ form }">
        <el-tabs v-model="activePlanType" type="card" class="w-full purchase-plan_type -mt-[11px] -ml-[10px]" @tab-click="changePlanType">
          <el-tab-pane label="FBA发货计划" :name="2"></el-tab-pane>
          <el-tab-pane label="海外仓发货计划" :name="1"></el-tab-pane>
        </el-tabs>
        <VGroup>
          <el-select v-model="form.input.type" style="width: 130px">
            <el-option label="发货计划编号" value="deliver_no"></el-option>
            <el-option label="备库需求单号" value="demand_no"></el-option>
            <el-option label="采购单号" value="purchase_no"></el-option>
            <el-option label="供应商名称" value="supplier_name"></el-option>
            <el-option label="产品名称" value="sku_name"></el-option>
            <el-option label="ASIN" value="asin"></el-option>
            <el-option label="备库单号" value="tc_deliver_no"></el-option>
          </el-select>
          <VBatchInput v-model="form.input.value" placeholder="请输入" class="w-40" @search="query" />
        </VGroup>
        <VGroup>
          <el-select v-model="form.skuInfo.type" class="w-28">
            <el-option label="sku" value="sku"></el-option>
            <el-option label="赛盒SKU" value="sai_he_sku"></el-option>
            <el-option label="自定义sku" value="custom_sku"></el-option>
          </el-select>
          <VBatchInput v-model="form.skuInfo.value" placeholder="请输入" class="w-40" @search="query" />
        </VGroup>
        <!-- <VSelect v-model="form.demand_type" placeholder="计划类型" :options="options.demand_type" multiple collapse-tags style="min-width: 160px" /> -->
        <VGroup>
          <el-select v-model="form.user.type" style="width: 130px">
            <el-option label="采购人员" value="purchase_user_id"></el-option>
            <el-option label="开发人员" value="develop_user_id"></el-option>
            <el-option label="供应商负责人员" value="director_id"></el-option>
            <el-option label="申请人员" value="create_user_id"></el-option>
            <el-option label="操作运营人员" value="operate_user_id"></el-option>
          </el-select>
          <VCascader v-model="form.user.value" placeholder="人员" multiple collapse-tags style="min-width: 160px" />
        </VGroup>
        <VBatchInput v-model="form.supplier_code" placeholder="供应商ID" class="w-40" @search="query" />
        <VCascader v-model="form.department_name" placeholder="需求部门" type="department" multiple collapse-tags checkStrictly style="min-width: 160px" />
        <VSelect v-model="form.plan_status" placeholder="计划状态" :options="options.plan_status" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.country" placeholder="国家" :options="options.country" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.destination_warehouse" placeholder="目的仓" :options="options.destination_warehouse" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.purchase_destination_warehouse" placeholder="发货仓" :options="options.purchase_destination_warehouse" multiple collapse-tags
          style="min-width: 160px" />
        <VSelect v-model="form.detail_purchase_status" placeholder="采购状态" :options="options.detail_purchase_status" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.prepare_type" placeholder="备货方式" :options="options.prepare_type" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.is_deliver_abnormal" placeholder="是否到货异常" :options="options.is_deliver_abnormal" multiple collapse-tags style="min-width: 160px" />
        <VCascader v-model="form.sale_id" placeholder="负责销售" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.transport_type" placeholder="运输方式" :options="options.transport_type" multiple collapse-tags style="min-width: 160px" />
        <VGroup>
          <div class="v-group-item">采购周期</div>
          <el-input-number v-model="form.purchase_day.start" placeholder="最小" :controls="false" :min="0" :step="1" :precision="0" class="w-32" />
          <div class="v-group-item">-</div>
          <el-input-number v-model="form.purchase_day.end" placeholder="最大" :controls="false" :min="0" :step="1" :precision="0" class="w-32" />
        </VGroup>
        <VSelect v-model="form.period_id" placeholder="结算方式" type="period" multiple collapse-tags style="min-width: 220px" />
        <el-input v-model="form.asin" placeholder="Asin" class="w-40" />
        <VSelect v-model="form.change_type" placeholder="计划类型变更" :options="options.change_type" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.platform" :options="options.platform" multiple collapse-tags style="min-width: 160px" placeholder="平台" />
        <VSelect v-model="form.is_new" placeholder="是否新品" :options="options.is_new" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.is_special_purchase" placeholder="是否特采" :options="options.is_special_purchase" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.is_dangerous" placeholder="是否危险品" :options="options.is_dangerous" multiple collapse-tags style="min-width: 160px" />
        <el-input v-model="form.remark" placeholder="计划备注" class="w-52" />
        <VGroup>
          <VSelect v-model="form.dateRange.type" :options="[{ label: '生成日期', value: 'create_time' }, { label: '发货日期', value: 'deliver_time' }]" style="width: 110px">
          </VSelect>
          <VDate v-model="form.dateRange.value" />
        </VGroup>
        <VSelect v-model="form.is_custom_product" :options="options.is_custom_product" multiple collapse-tags filterable clearable style="min-width: 140px" placeholder="是否定制化" />
        <teleport v-if="demandTabsLoad" to="#demand-tabs">
          <el-tabs v-model="form.type" class="w-full" @tab-change="changePurchaseStatus">
            <el-tab-pane v-for="(d, i) in labelTotal" :key="i" :label="`${d.label}(${d.num || 0})`" :name="d.value"></el-tab-pane>
          </el-tabs>
        </teleport>
      </template>
      <template #form_handle>
        <el-button type="primary" @click="query()">查询</el-button>
        <el-button @click="resetForm">重置</el-button>
      </template>
      <template #toolbar_btns>
        <div id="demand-tabs" class="w-full" v-dom-load="() => demandTabsLoad = true"></div>
        <VButton auth="/purchase/demand/deliver/add" type="primary" @click="create"><i class="dk-iconfont icon-Plus" />添加</VButton>
          <VButton auth="/purchase/demand/deliver/generate_fba_backup_order" type="primary" @click="handleBatch('fba','/head_procedure/orderManagement/fbaOrderManagementV2/add')">
              <svg-icon icon-class="sc" class="mr-1" style="font-size: 15px" />生成FBA备库订单
          </VButton>



<!--        <VAuth auth="/purchase/demand/deliver/generate_fba_backup_order">-->
<!--          <el-dropdown trigger="click" @command="(val)=>handleBatch('fba',val)">-->
<!--            <el-button type="primary">-->
<!--              <svg-icon icon-class="sc" class="mr-1" style="font-size: 15px" />生成FBA备库订单-->
<!--            </el-button>-->
<!--            <template #dropdown>-->
<!--              <el-dropdown-menu>-->
<!--                <el-dropdown-item command="/head_procedure/orderManagement/fbaOrderManagement/addFba">生成FBA备库订单</el-dropdown-item>-->
<!--                <el-dropdown-item command="/head_procedure/orderManagement/fbaOrderManagementV2/add">生成FBA备库订单V2</el-dropdown-item>-->
<!--              </el-dropdown-menu>-->
<!--            </template>-->
<!--          </el-dropdown>-->
<!--        </VAuth>-->
        <VButton auth="/purchase/demand/deliver/generate_fba_backup_order" type="primary" @click="handleBatch('oversea')">
          <svg-icon icon-class="sc" class="mr-1" style="font-size: 15px" />生成海外仓备库订单
        </VButton>
        <VButton auth="/purchase/demand/deliver/confirm" @click="handleBatch('confirm')">运营确认</VButton>
        <el-tooltip content="可批量修改ASIN、国家、实际运输方式、派送方式、预计发货日期、发货
  仓、目的仓" placement="top" effect="dark">
          <VButton auth="/purchase/demand/deliver/edit" @click="handleBatch('edit')">批量修改</VButton>
        </el-tooltip>

        <VButton auth="/purchase/demand/deliver/submit" @click="handleBatch('submit')">批量提交</VButton>
        <VButton auth="/purchase/demand/deliver/unaudit" @click="handleBatch('unAudit')">批量反审</VButton>
        <VButton auth="/purchase/demand/deliver/revoke" @click="handleBatch('revoke')">批量撤回</VButton>
        <VButton auth="/purchase/demand/deliver/void" @click="handleBatch('cancel')">批量作废</VButton>
        <VButton auth="/purchase/demand/deliver/remark" @click="handleBatch('remark')">批量修改计划备注</VButton>
        <VButton v-if="activePlanType==1" auth="/purchase/demand/deliver/reserveOrder" @click="handleReserveOrder">自动生成备库单</VButton>
        <VTotal :data="total" :options="[{ title: '商品总体积（m³）', key: 'volume' }, { title: '商品总重量（KG）', key: 'weight' },{ title: '头程总体积（m³）', key: 'tc_volume' }, { title: '头程总重量（KG）', key: 'tc_weight' }, { title: 'sku总数量', key: 'deliver_num' }]" class="ml-auto" />
        <VImport auth="/purchase/demand/deliver/add" :tableRef="tableRef" importUrl="/v1/purchase-demand/deliver-plan/import"
          downloadUrl="https://xc-pms.oss-cn-shenzhen.aliyuncs.com/template/deliver_plan.xlsx" class="ml-auto" @success="query" />
        <VAuth auth="/purchase/demand/deliver/export">
          <el-dropdown trigger="click" @command="handleExport">
            <el-button>
              <i class="dk-iconfont icon-Upload" />
              导出<i class="dk-iconfont icon-ArrowDown" />
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="deliver_plan">发货计划维度</el-dropdown-item>
                <el-dropdown-item command="deliver-plan-tc">头程单维度</el-dropdown-item>
                <el-dropdown-item command="deliver-plan-box">箱维度</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <VExport class="absolute -right-full" ref="exportRef" mainKey="dp_id" :name="exportName" :tableRef="tableRef" task />
        </VAuth>
      </template>
    </VTable>
    <Add ref="addRef" :options="options" @success="query" />
    <!-- <Adjust ref="adjustRef" :options="options" @success="query" /> -->
    <Confirm ref="confirmRef" @success="query" />
    <OrderChange ref="orderChangeRef" :options="options" @success="query" />
    <BatchEdit ref="batchEditRef" :options="options" @success="query" />
    <ReserveOrder ref="reserveOrderRef" @success="query" />
    <VLog ref="logRef" />
  </VPage>
</template>

<script setup lang="jsx" name="Account">
import api from './api'
import Add from './components/Add'
// import Adjust from './components/Adjust'
import BatchEdit from './components/BatchEdit'
import Confirm from './components/Confirm'
import OrderChange from './components/OrderChange'
import VTotal from '@/components/VTotal'
import VImport from '@/components/VImport'
import { getOption } from '@/api/public'
import { ElMessage, ElMessageBox } from 'element-plus'
import { to } from '@/utils/action'
import { resMessage } from '@/utils/res'
import DeliveryPlan from './components/DeliveryPlan.vue'
import SimpleTable from '@/components/SimpleTable'
import ReserveOrder from './components/ReserveOrder'
const router = useRouter()
const route = useRoute()

const baseName = 'deliver_plan'
const tableRef = ref()
const logRef = ref()
const loadings = reactive({})
const demandTabsLoad = ref(false)

// 导出
const exportName = ref('deliver_plan')
const exportRef = ref()
const handleExport = (val) => {
  if(val === 'deliver-plan-box') {
    api.exportBox({ dp_ids: tableRef.value.$table.getCheckboxRecords().map(d => d.dp_id), ...tableRef.value.getQueryForm() }).then(res => {
      ElMessageBox.alert(res.message, '提示')
    })
    return
  }
  exportName.value = val
  nextTick(() => {
    exportRef?.value.open()
  })
}

// 查询
const query = () => {
  tableRef?.value.query()
}

const deliveryPlanRef = ref()
// 重置
const resetForm = () =>{
  tableRef.value.setForm({
    plan_type: activePlanType.value
  })
  activeStatus.value = 0
  deliveryPlanRef?.value.query()
  tableRef?.value.query()
}

// 添加
const addRef = ref()
const create = () => {
  addRef?.value.open()
}

// 数据统计
const total = ref({})
const labelTotal = ref([])

const getTotal = () =>{
  const form = tableRef?.value.getQueryForm()
  api.total(form).then(res => {
    total.value = res.data
  })
  api.labelTotal(form).then(res => {
    labelTotal.value = res.data
  })
}

onMounted(() => {
  getTotal()
})

// 获取options
const options = ref({})
Promise.all([
  getOption({ type: 'purchase_demand' }).then(res => res.data),
  getOption({ type: 'purchase' }).then(res => res.data),
  getOption({ type: baseName }).then(res => res.data),
  api.processDeliveryMethod().then(res => ({ processDeliveryMethod: res.data })),
  Promise.resolve({ test: [{ label: 'test', value: 1 }] })
]).then(res => {
  options.value = res.reduce((acc, cur) => (((acc = { ...acc, ...cur }), acc)), {})
})

const reserveOrderRef = ref()
// 批量操作
const batchEditRef = ref()
const handleBatch = (name,type=null) => {
  const selection = tableRef.value.$table.getCheckboxRecords()
  if (!selection.length) {
    ElMessage.warning('请先选择行')
    return
  }
  const showLoading = () => loadings[name] = true
  const closeLoading = () => loadings[name] = false
  const { dp_ids, shipment_type } = selection.reduce((pre, cur) => {
    const { dp_id, purchase } = cur
    pre.dp_ids.push(dp_id)
    if (!pre.shipment_type && purchase && Array.isArray(purchase) && purchase.length) {
      pre.shipment_type = purchase[0].prepare_type
    }
    return pre
  }, { dp_ids: [], shipment_type: '' })
  const handle = {
    edit: () => {
      batchEditRef?.value.open(dp_ids)
    },
    revoke: async () => {
      showLoading()
      const res = await api.revoke({ dp_ids })
      closeLoading()
      resMessage({
        res,
        success: () => {
          ElMessage.success('操作成功')
          query()
          closeLoading()
        }
      })
    },
    fba: () => {
      showLoading()
      api.getFba({ dp_ids, plan_type: 2 }).then(res => {
        const { destination_warehouse: send_warehouse_id, shop_id: to_shop_id, deliver_time: plan_shipment_time, delivery_method: transport_type, transport_type: transport, detail, demand_warehouse: to_warehouse_id } = res.data
        const commodity = detail.map(d => {
          const { sku, sale_id: sale_user_id, deliver_num: quantity, purchase_no: po_number, deliver_plan_no: pms_plan_no } = d
          return { sku, sale_user_id, quantity, po_number, pms_plan_no }
        })
        const query = {
          type: 'add',
          skuType: 'sku',
          plan_shipment_time,
          transport,
          transport_type,
          shipment_type,
          commodity: JSON.stringify(commodity)
        }
        const ids = {
          send_warehouse_id,
          to_warehouse_id,
          to_shop_id,
        }
        for (const key in ids) {
          const value = ids[key]
          if (value) {
            query[key] = value
          }
        }
        to({ path: type, query })
      }).finally(closeLoading)
    },
    oversea: () => {
      showLoading()
      api.getFba({ dp_ids, plan_type: 1 }).then(res => {
        const { destination_warehouse: send_warehouse_id, shop_id: to_shop_id, deliver_time: plan_shipment_time, delivery_method: transport_type,transport_type: transport, detail, demand_warehouse: to_warehouse_id } = res.data
        const commodity = detail.map(d => {
          const { sku, sale_id: sale_user_id, deliver_num: quantity, purchase_no: po_number, deliver_plan_no: pms_plan_no } = d
          return { sku, sale_user_id, quantity, po_number, pms_plan_no }
        })
        const query = {
          type: 'add',
          skuType: 'sku',
          plan_shipment_time,
          transport_type,
          transport,
          shipment_type,
          commodity: JSON.stringify(commodity)
        }
        const ids = {
          send_warehouse_id,
          to_warehouse_id,
          to_shop_id,
        }
        for (const key in ids) {
          const value = ids[key]
          if (value) {
            query[key] = value
          }
        }
        to({ path: '/head_procedure/orderManagement/warehouseList/addFbaSea', query })
      }).finally(closeLoading)
    },
    cancel: () => {
      ElMessageBox.confirm('是否确认作废？', '取消', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(() => {
          showLoading()
          api.cancel({ dp_ids }).then(res => {
            resMessage({
              res,
              success: () => {
                ElMessage.success('操作成功')
                query()
              }
            })
          }).finally(closeLoading)
        })
        .catch(() => {
          ElMessage({ type: 'info', message: '取消操作', })
        })
    },
    submit: () => {
      showLoading()
      api.batchSubmit({ dp_ids }).then(res => {
        ElMessage.success('操作成功')
        query()
      }).finally(closeLoading)
    },
    confirm: () => {
      confirmRef?.value.open(dp_ids)
    },
    unAudit: () => {
      let dp_ids = selection?.filter(d => d.deliver_status == 3)?.map(d => d.dp_id)
      if (!dp_ids?.length) return ElMessage.warning('请选择待建单的数据!')
      showLoading()
      api.batchAuditBack({ dp_ids }).then(res => {
        ElMessage.success('操作成功')
        query()
      }).finally(closeLoading)
    },
    remark: () => {
      ElMessageBox.prompt('备注', '批量修改计划备注', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: (val) => !val ? '不能为空' : true,
        inputType: 'textarea',
      })
        .then(({ value }) => {
          showLoading()
          api.remark({dp_ids, remark: value}).then(res => {
          resMessage({
            res,
            success: () => {
              ElMessage.success('操作成功')
              query()
            }
        }).finally(closeLoading)
      })
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '取消操作',
          })
        })
    },
  }
  handle[name]()
}

const handleReserveOrder = () => {
  const selection = tableRef.value.$table.getCheckboxRecords();
  const dp_ids = selection?.map(item => item.dp_id);
  const form = tableRef.value.getQueryForm()
  const dataToPass = dp_ids?.length ? {dp_ids} : form;
  reserveOrderRef.value.open(dataToPass);
}
// 单行操作
// const adjustRef = ref()
const confirmRef = ref()
const orderChangeRef = ref()
const handleRow = (name, row, rowIndex) => {
  const { dp_id } = row
  const showLoading = () => {
    loadings[name + rowIndex] = true
  }
  const closeLoading = () => {
    loadings[name + rowIndex] = false
  }
  const handle = {
    orderChange: () => {
      orderChangeRef?.value.open(dp_id,row)
    },
    revoke: async () => {
      showLoading()
      const res = await api.revoke({ dp_ids: [dp_id] })
      closeLoading()
      resMessage({
        res,
        success: () => {
          ElMessage.success('操作成功')
          query()
          closeLoading()
        }
      })
    },
    submit: () => {
      showLoading()
      api.batchSubmit({ dp_ids:[dp_id] }).then(res => {
        ElMessage.success('操作成功')
        query()
      }).finally(closeLoading)
    },
    cancel: () => {
      ElMessageBox.confirm('是否确认作废？', '取消', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(() => {
          showLoading()
          api.cancel({ dp_ids: [dp_id] }).then(res => {
            resMessage({
              res,
              success: () => {
                ElMessage.success('操作成功')
                query()
              }
            })
          }).finally(closeLoading)
        })
        .catch(() => {
          ElMessage({ type: 'info', message: '取消操作', })
        })
    },
    // adjust: () => {
    //   adjustRef?.value.open(row)
    // },
    edit: () => {
      addRef?.value.open(dp_id)
    },
    confirm: () => {
      confirmRef?.value.open([dp_id])
    },
    log: () => {
      logRef?.value.open({ log_type: baseName, dp_id })
    },
    toDemand: () => {
      sessionStorage.setItem('_table_form', JSON.stringify({ tableForm: { input: { type: 'demand_no', value: row.demand_no } } }))
      router.push('/demand/demand')
    },
    toPurchase: () => {
      sessionStorage.setItem('_table_form', JSON.stringify({ tableForm: { input: { type: 'purchase_no', value: row.purchase_no } } }))
      router.push('/manage/purchase')
    },
    toProduct: () => {
      sessionStorage.setItem('_table_form', JSON.stringify({ tableForm: { skuInfo: { type: 'sku', value: row.sku } } }))
      router.push('/product/product')
    },
    unAudit: () => {
      ElMessageBox.confirm('是否确认反审到待提交状态', '反审', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(() => {
          showLoading()
          api.batchAuditBack({ dp_ids: [dp_id] }).then(res => {
            ElMessage.success('操作成功')
            query()
          }).finally(closeLoading)
        })
        .catch(() => {
          ElMessage({ type: 'info', message: '取消操作', })
        })
    },
    remark: () => {
      const {remark} = row
      api.remark({dp_ids: [dp_id], remark}).then(res => {
        resMessage({
          res,
          success: () => {
            ElMessage.success('操作成功')
          }
        })
      })
    },
    operateRemark: () => {
      const {audit_remark} = row
      api.updateOperateReject({dp_id, audit_remark}).then(res => {
        ElMessage.success('操作成功')
      })
    },
  }
  handle[name]()
}

// 点击发货计划
const changeDeliverTime = (date) =>{
  tableRef?.value.setFormField('dateRange', { type: 'deliver_time', value: date, range: true })
  query()
}

const activePlanType = ref(2)
const activeStatus = ref(0)
// 发货计划类型切换
const changePlanType = (val)=>{
  // const form = tableRef.value.getForm()
  tableRef.value.setForm({
    plan_type: val.props.name
  })
  deliveryPlanRef.value.query(val.props.name)
  query()
}

// watch(()=>route.query,(val)=>{
//   if(val?.plan_type){
//     nextTick(() => {
//   const form = tableRef.value.getForm()
//     activePlanType.value = Number(val?.plan_type)
//     tableRef.value.setForm({
//       ...form,
//       plan_type:activePlanType.value
//     })
//     query()
//     })
//   }
// },{deep:true,immediate:true})
watchEffect(async () => {
  const { plan_type } = route.query || {};
  if (plan_type) {
    await nextTick();
    const form = tableRef.value.getForm();
    activePlanType.value = Number(plan_type);
    tableRef.value.setForm({
      ...form,
      plan_type: activePlanType.value,
    });
    query();
  }
});
// 发货状态切换
const changePurchaseStatus = (val) =>{
  // const form = tableRef.value.getForm()
  // const plan_status = val.props.name ?[val.props.name]: ''
  // tableRef.value.setForm({
  //   ...form,
  //   plan_status
  // })
  query()
}

// 
const changePlanStatus = (val) =>{
  console.log(val)
  if(val.length){}
}

// 列表配置
const tableOptions = reactive({
  rowConfig: { height: 250 },
  showHeaderOverflow: false,
  showOverflow: false,
  rowClassName: ({row}) => row.deliver_status === 6 ? 'purchase-bg-error' : '',
  formConfig: {
    data: {
      type: 0,
      input: { type: 'deliver_no', value: '' },
      skuInfo: { type: 'sku', value: '' },
      user: { type: 'purchase_user_id', value: [] },
      purchase_day: {},
      dateRange: { type: 'deliver_time', value: [], range: true },
      plan_type: 2,
    }
  },
  columns: [
    { type: 'checkbox', width: 40, fixed: 'left' },
    {
      minWidth: 160, slots: {
        header: () => <div>发货计划编号</div>,
        default: ({ row }) => <div>
          <VText value={row.deliver_no} copy />
          <VText title='计划状态' value={row.deliver_status_name} />
          <VText title='是否延期' value={row.is_delay_name} />
          <VText title='计划类型变更' value={row.change_type_name} title-position='top' />
          <VText title='创建人' value={row.create_user} />
        </div>
      }
    },
    {
      minWidth: 300, slots: {
        header: () => <div>备库需求信息</div>,
        default: ({ row }) => <div>
          <VText title="需求ID" value={row.sku_no} />
          <VText type='link' value={row.demand_no} copy onClick={() => handleRow('toDemand', row)}></VText>
          <VText title='备库类型' value={row.demand_type_name} />
          <VText title='平台' value={row.platform_name} />
          <VText title='目的仓' value={row.destination_warehouse_name} />
          <VText title='需求日期' value={row.demand_time} />
          <div class="grid grid-cols-2 gap-x-1">
            <VText title='需求数量' value={row.demand_num}></VText>
            <VText title='总箱数' value={row.total_box}></VText>
            <VText title='实际重(kg)' value={row.total_weight}></VText>
            <VText title='体积重(kg)' value={row.volume_weight}></VText>
            <VText title='计费重(kg)' value={row.price_weight}></VText>
            <div class="text-[#5b831c]">抛率: {row.throw_rate || '-'}</div>
          </div>
          <VText title='体积(CBM)' value={row.volume}></VText>
        </div>
      }
    },
    {
      minWidth: 220, slots: {
        header: () => <div>采购单信息</div>,
        default: ({ row, rowIndex }) => {
          return <VMore key={rowIndex}>
            {{
              default: () => row.purchase?.map(d => <div class='w-full'>
                <VText value={d.purchase_no} type='link' copy onClick={() => handleRow('toPurchase', d)}></VText>
                <div class="font-bold">供应商代码:{d.supplier_code}</div>
                <VText title='备货方式' value={d.prepare_type_name} />
                <VText title='收货仓' value={d.destination_warehouse_name} />
                <VText title='采购员' value={d.purchase_user} />
                <div class="flex gap-2">
                  <div class="font-bold mr-1">下单数:{d.purchase_num}</div>
                  <div class="font-bold text-red-600">不良数:{d.reject_num}</div>
                </div>
                <VText title='入库数' value={d.inbound_num}></VText>
                <VText title='联系人' value={d.name}></VText>
                <VText title='联系电话' value={d.tel}></VText>
                <VText title='供应商地址' value={d.factory_area_name}></VText>
                <VText title='装柜地址' value={d.factory_address}></VText>
              </div>)
            }}
          </VMore>
        }
      }
    },
    {
      minWidth: 240, slots: {
        header: () => <div>销售信息</div>,
        default: ({ row }) => <div>
          <VText value={row.country_name} />
          <div class={`mr-2 icon zhandian-iconfont mb-2 mt-2 icon-zhandian_${row?.country?.toLowerCase()}`}></div>
          {activePlanType.value == 2 ?<VText value={row.asin} />:''} 
          <VText value={row.department_name} line={2} />
          <VText title='操作运营人员' value={row.operate_user_name} line={2} />
          <div class="font-bold">销售:{row.sale_name}</div>
        </div>
      }
    },
    {
      minWidth: 220, slots: {
        header: () => <div>SKU信息</div>,
        default: ({ row }) => <div>
          <VImage src={row.main_img} class="w-20 h-20 absolute right-0 top-2" />
          {row.is_dangerous === 2 ? <svg t="1731396340885" class="-mt-[1px]" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="7755" width="24" height="24"><path d="M426.14784 160.23552l-368.27136 628.736a102.4 102.4 0 0 0 88.35072 154.17344h736.54272a102.4 102.4 0 0 0 88.35072-154.17344l-368.2304-628.736a102.4 102.4 0 0 0-176.7424 0z" fill="#FADE14" p-id="7756"></path><path d="M545.54624 158.96576a61.44 61.44 0 0 1 21.95456 21.99552l368.27136 628.736a61.44 61.44 0 0 1-53.00224 92.48768H146.2272a61.44 61.44 0 0 1-53.00224-92.48768l368.2304-628.736a61.44 61.44 0 0 1 84.09088-21.99552z m-63.73376 28.34432l-2.6624 3.97312-368.27136 628.736a40.96 40.96 0 0 0 30.55616 61.44l4.79232 0.24576h736.54272a40.96 40.96 0 0 0 37.51936-57.42592l-2.17088-4.25984-368.27136-628.736a40.96 40.96 0 0 0-68.03456-3.97312z" fill="#333333" p-id="7757"></path><path d="M450.1504 397.47584a385.26976 385.26976 0 0 1-123.2896 123.2896l19.6608 23.7568c12.288-8.6016 24.576-17.6128 36.864-27.4432v85.1968c-1.6384 67.1744-20.48 119.1936-56.5248 156.8768l23.7568 21.2992c39.3216-44.6464 60.2112-104.0384 62.2592-178.176v-66.7648h277.2992v-28.672h-121.6512c16.384-13.9264 33.1776-31.1296 49.9712-50.7904v-21.2992h-158.1056c6.9632-9.8304 13.5168-20.0704 20.0704-30.72l-30.3104-6.5536z m79.872 109.3632H395.6736c15.9744-14.336 31.1296-29.9008 45.4656-46.6944h138.8544c-16.384 17.6128-33.1776 33.1776-49.9712 46.6944z m73.728 101.5808v38.0928c0 13.1072-5.3248 19.6608-15.9744 19.6608-14.7456 0-31.1296-0.8192-49.152-2.4576l6.9632 27.8528c17.2032 0.8192 34.816 1.2288 52.8384 1.2288 23.3472-0.8192 35.2256-13.5168 35.2256-37.2736v-73.3184h-169.1648v153.6c0 24.576 13.1072 36.864 40.1408 36.864h129.4336c23.3472 0 39.3216-3.6864 47.5136-10.24 9.0112-8.192 15.1552-30.72 18.8416-66.7648l-28.2624-9.0112c-2.4576 23.7568-5.7344 39.7312-10.6496 47.9232-4.5056 6.9632-16.384 10.6496-35.2256 10.6496h-109.7728c-14.7456 0-22.1184-6.5536-22.1184-19.2512v-117.5552h109.3632z" fill="#333333" p-id="7758"></path></svg> : ''}
          <VText value={row.sku} copy />
          <div class="font-bold text-red-600">发货数量:{row.deliver_num}</div>
          <VText title="物流属性" value={row.logistics_attributes_name} />
          <VText title="新品" value={row.is_new == 1? '否':row.is_new == 2? '是':''} />
          <VText title="组合SKU" value={row.is_combination == 1? '否':row.is_combination == 2? '是':''} />
          <VText line={2} value={row.sku_cn_title} />
          <VText title='是否定制化' value={row.is_custom_product_name} />
        </div>
      }
    },
    {
      minWidth: 120, slots: {
        header: () => <div>辅助关系</div>,
        default: ({ row }) => <div>
          <VText value={row.main_sku} title="主"></VText>
          <VText value={row.ass_sku} title="辅">
            {row?.ass_sku?.map(item=>{
              return <div>{item.sku}*{item.quantity_auxiliary}</div>
            })}
          </VText>
        </div>
      }
    },
    {
      minWidth: 160, slots: {
        header: () => <div>单箱尺寸信息(商品)</div>,
        default: ({ row }) => <div>
          <VText title='长' value={row.length + 'CM'}></VText>
          <VText title='宽' value={row.width+ 'CM'}></VText>
          <VText title='高' value={row.height+ 'CM'}></VText>
          <VText title='单箱数量' value={row.packing_qty}></VText>
          <VText title='单箱重量' value={row.packing_gross_weight_kg + 'KG'}></VText>
        </div>
      }
    },
    {
      minWidth: 160, slots: {
        header: () => <div>单箱尺寸信息(头程)</div>,
        default: ({ row, rowIndex }) => (
          <div>
            <VMore key={rowIndex}>
              {{
                default: (line) =>
                  (row.box_data || []).map((d) => (
                    <div class="w-full">
                      <VText title='长' value={d.length + 'CM'} line={line}></VText>
                      <VText title='宽' value={d.width+ 'CM'} line={line}></VText>
                      <VText title='高' value={d.height+ 'CM'} line={line}></VText>
                      <VText title='单箱数量' value={d.unit_box_num} line={line}></VText>
                      <VText title='单箱重量' value={d.unit_weight + 'KG'} line={line}></VText>
                    </div>
                  )),
              }}
            </VMore>
          </div>
        ),
      }
    },
    {
      minWidth: 350, slots: {
        header: () => <div>发货方式</div>,
        default: ({ row }) => <div>
          <VText title="发货仓" value={row.shipping_warehouse_name} />
          {activePlanType.value == 1 ? <VText title="目的仓" value={row.plan_destination_warehouse_name} />:''} 
          <VText title="运输方式" value={row.transport_type_name} />
          <div class="text-red-600">派送方式: {row.delivery_method_name || '-'}</div>
          <VText title="发货日期" value={row.deliver_time} />
        </div>
      }
    },
    {
      minWidth: 120, slots: {
        header: () => <div>运营驳回原因</div>,
        default: ({ row }) => <div>
          <div class="mb-2">
            <VSelect v-model={row.operate_reject_reason} placeholder="请选择" select options={options.value.operate_reject_reason} class='w-full' onChange={() => handleRow('operateRemark', row)}/>
          </div>
          <el-input v-model={row.audit_remark} type="textarea" rows={3} placeholder="请输入" onChange={() => handleRow('operateRemark', row)} />
        </div>
      }
    },
    {
      minWidth: 120, slots: {
        header: () => <div>计划备注</div>,
        default: ({ row }) => <div>
          <el-input v-model={row.remark} type="textarea" rows={6} placeholder="请输入" onChange={() => handleRow('remark', row)} />
        </div>
      }
    },
    {
      minWidth: 100, slots: {
        header: () => <div>驳回原因</div>,
        default: ({ row }) => <VText value={row.audit_remark} line={3} />
      }
    },
    {
      minWidth: 260, slots: {
        header: () => <div>头程出库信息</div>,
        default: ({ row, rowIndex }) => {
          return <VMore key={rowIndex} width={1000}>
            {{
              default: (line) => line > 1 ? <SimpleTable columns={[
            { title: '下单时间', field: 'create_time', span: 4 }, 
            { title: '出库单号', field: 'deliver_no', span: 4 }, 
            { title: '目的仓编码', field: 'fba_code', span: 3 },
            { title: '目的仓', field: 'warehouse_name', span: 5 },
            { title: '物流渠道', field: 'channel_name', span: 3 },
            { title: '出库数量', field: 'quantity', span: 2 },
            { title: '状态', field: 'status', span: 2 },
          ]} data={row.deliver} line={100} /> : 
              row.deliver?.map(d => <div>
                <VText title='下单时间' value={d.create_time} />
                <VText title='出库单号' value={d.deliver_no} />
                <div class="text-red-600">目的仓编码: {d.fba_code || '-'}</div>
                <VText title='目的仓' value={d.warehouse_name} />
                <VText title='物流渠道' value={d.channel_name} />
                <VText title='出库数量' value={d.quantity}></VText>
                <VText title='状态' value={d.status}></VText>
              </div>)
            }}
          </VMore>
        }
      }
    },
    {
      title: '操作', width: 120, fixed: 'right', slots: {
        default: ({ row, rowIndex }) => {
          const { deliver_status } = row
          // deliver_status	计划状态: 1待提交2待运营接收3待建单4部分建单5已建单6已作废7已驳回
          return [<div class='nm flex flex-wrap gap-x-2 gap-y-1'>
            {[3].includes(deliver_status) ? <VButton auth="/purchase/demand/deliver/unaudit" link type="primary" onClick={() => handleRow('unAudit', row, rowIndex)}>反审</VButton> : ''}
            {[1, 7].includes(deliver_status) ? <VButton auth="/purchase/demand/deliver/submit" link type="primary" loading={loadings['submit' + rowIndex]} onClick={() => handleRow('submit', row, rowIndex)}>提交</VButton> : ''}
            {[1, 6, 7].includes(deliver_status) ? <VButton auth="/purchase/demand/deliver/edit" link type="primary" onClick={() => handleRow('edit', row, rowIndex)}>编辑</VButton> : ''}
            {[2].includes(deliver_status) ? <VButton auth="/purchase/demand/deliver/confirm" link type="primary" onClick={() => handleRow('confirm', row, rowIndex)}>运营确认</VButton> : ''}
            {[2].includes(deliver_status) ? <VButton auth="/purchase/demand/deliver/revoke" link type="primary" onClick={() => handleRow('revoke', row, rowIndex)}>撤回</VButton> : ''}
            {[1, 7].includes(deliver_status) ? <VButton auth="/purchase/demand/deliver/void" link type="primary" loading={loadings['cancel' + rowIndex]} onClick={() => handleRow('cancel', row, rowIndex)}>作废</VButton> : ''}
            {[3,4,5].includes(deliver_status) ? <VButton auth="/purchase/demand/deliver/orderChange" link type="primary" loading={loadings['orderChange' + rowIndex]} onClick={() => handleRow('orderChange', row, rowIndex)}>建单后变更</VButton> : ''}
            <VButton auth="/purchase/demand/deliver/logs" link type="primary" onClick={() => handleRow('log', row, rowIndex)}>日志</VButton>
          </div>]
        }
      }
    },
  ],
  proxyConfig: {
    autoLoad: false,
    ajax: {
      query: async ({ page, form }) => {
        await getTotal({ ...form, ...page })
        return api.query({ ...form, ...page })
      }
    }
  }
})
</script>
<style lang="scss">
.purchase-plan_type {
  .el-tabs__header {
    margin-bottom: 0;
  }
}
.purchase-bg-error {
  td {
    &::before {
      content: '';
      position: absolute;
      inset: 0;
      background-color: rgba(244, 108, 108, 0.2);
    }
    .vxe-cell {
      position: relative;
    }
  }
}
</style>